<template>
  <div class="reports-container">
    <div class="page-header">
      <h2>财务报表</h2>
      <div class="header-actions">
        <el-select v-model="reportType" placeholder="选择报表类型" @change="handleReportTypeChange">
          <el-option label="日报表" value="daily" />
          <el-option label="月报表" value="monthly" />
          <el-option label="年报表" value="yearly" />
          <el-option label="渠道分析" value="channel" />
          <el-option label="商品分析" value="product" />
        </el-select>
        
        <el-date-picker
          v-if="reportType === 'daily'"
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :disabled-date="disabledDate"
          @change="handleDateChange"
        />
        
        <el-date-picker
          v-if="reportType === 'monthly'"
          v-model="monthValue"
          type="month"
          placeholder="选择月份"
          @change="handleMonthChange"
        />
        
        <el-date-picker
          v-if="reportType === 'yearly'"
          v-model="yearValue"
          type="year"
          placeholder="选择年份"
          @change="handleYearChange"
        />
        
        <el-button type="primary" @click="generateReport">生成报表</el-button>
        <el-button @click="exportReport" :disabled="!hasReportData">导出Excel</el-button>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <!-- 报表内容 -->
    <div v-else-if="hasReportData" class="report-content">
      <!-- 销售概览 -->
      <div class="overview-cards">
        <el-card class="overview-card">
          <template #header>
            <div class="card-header">
              <span>总销售额</span>
            </div>
          </template>
          <div class="card-value">¥{{ formatNumber(reportData.totalSales) }}</div>
          <div class="card-compare" :class="{ 'up': reportData.salesGrowth > 0, 'down': reportData.salesGrowth < 0 }">
            较上期: {{ reportData.salesGrowth > 0 ? '+' : '' }}{{ reportData.salesGrowth }}%
          </div>
        </el-card>
        
        <el-card class="overview-card">
          <template #header>
            <div class="card-header">
              <span>订单数</span>
            </div>
          </template>
          <div class="card-value">{{ reportData.orderCount }}</div>
          <div class="card-compare" :class="{ 'up': reportData.orderGrowth > 0, 'down': reportData.orderGrowth < 0 }">
            较上期: {{ reportData.orderGrowth > 0 ? '+' : '' }}{{ reportData.orderGrowth }}%
          </div>
        </el-card>
        
        <el-card class="overview-card">
          <template #header>
            <div class="card-header">
              <span>客单价</span>
            </div>
          </template>
          <div class="card-value">¥{{ formatNumber(reportData.averageOrder) }}</div>
          <div class="card-compare" :class="{ 'up': reportData.averageGrowth > 0, 'down': reportData.averageGrowth < 0 }">
            较上期: {{ reportData.averageGrowth > 0 ? '+' : '' }}{{ reportData.averageGrowth }}%
          </div>
        </el-card>
        
        <el-card class="overview-card">
          <template #header>
            <div class="card-header">
              <span>退款金额</span>
            </div>
          </template>
          <div class="card-value">¥{{ formatNumber(reportData.refundAmount) }}</div>
          <div class="card-compare">退款率: {{ reportData.refundRate }}%</div>
        </el-card>
      </div>
      
      <!-- 销售趋势图 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>销售趋势</span>
          </div>
        </template>
        <div class="chart-container">
          <!-- 实际项目中使用ECharts或其他图表库 -->
          <div class="mock-chart">
            <div class="chart-placeholder">
              <div v-for="(item, index) in reportData.salesTrend" :key="index" 
                   class="chart-bar" 
                   :style="{ height: `${item.value / 2}px` }">
                <div class="bar-tooltip">{{ item.date }}: ¥{{ formatNumber(item.value) }}</div>
              </div>
            </div>
            <div class="chart-labels">
              <div v-for="(item, index) in reportData.salesTrend" :key="index" class="chart-label">
                {{ item.shortDate }}
              </div>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 支付方式分布 -->
      <div class="two-column">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>支付方式分布</span>
            </div>
          </template>
          <div class="payment-distribution">
            <div class="payment-item" v-for="(item, method) in reportData.paymentDistribution" :key="method">
              <div class="payment-name">{{ getPaymentMethodName(method) }}</div>
              <div class="payment-bar-container">
                <div class="payment-bar" :style="{ width: `${item.percentage}%`, backgroundColor: getPaymentColor(method) }"></div>
                <span class="payment-percentage">{{ item.percentage }}%</span>
              </div>
              <div class="payment-amount">¥{{ formatNumber(item.amount) }}</div>
            </div>
          </div>
        </el-card>
        
        <!-- 渠道销售分布 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>渠道销售分布</span>
            </div>
          </template>
          <div class="channel-distribution">
            <div class="channel-item" v-for="(item, index) in reportData.channelDistribution" :key="index">
              <div class="channel-name">{{ item.name }}</div>
              <div class="channel-bar-container">
                <div class="channel-bar" :style="{ width: `${item.percentage}%`, backgroundColor: getChannelColor(index) }"></div>
                <span class="channel-percentage">{{ item.percentage }}%</span>
              </div>
              <div class="channel-amount">¥{{ formatNumber(item.amount) }}</div>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 热销商品排行 -->
      <el-card class="table-card">
        <template #header>
          <div class="card-header">
            <span>热销商品排行</span>
          </div>
        </template>
        <el-table :data="reportData.topProducts" style="width: 100%">
          <el-table-column prop="rank" label="排名" width="80" />
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="quantity" label="销售数量" width="120" />
          <el-table-column prop="amount" label="销售金额" width="150">
            <template #default="scope">
              ¥{{ formatNumber(scope.row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="percentage" label="占比" width="120">
            <template #default="scope">
              {{ scope.row.percentage }}%
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    
    <!-- 无数据提示 -->
    <el-empty v-else description="请选择报表类型和日期范围，然后点击生成报表" />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 状态数据
const loading = ref(false)
const reportType = ref('daily')
const dateRange = ref([])
const monthValue = ref('')
const yearValue = ref('')
const reportData = ref(null)

// 计算属性
const hasReportData = computed(() => reportData.value !== null)

// 禁用未来日期
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

// 处理报表类型变化
const handleReportTypeChange = () => {
  reportData.value = null
  dateRange.value = []
  monthValue.value = ''
  yearValue.value = ''
}

// 处理日期范围变化
const handleDateChange = () => {
  reportData.value = null
}

// 处理月份变化
const handleMonthChange = () => {
  reportData.value = null
}

// 处理年份变化
const handleYearChange = () => {
  reportData.value = null
}

// 生成报表
const generateReport = async () => {
  // 验证输入
  if (!validateInput()) {
    return
  }
  
  loading.value = true
  try {
    // 调用实际API，不再使用模拟数据
    const api = await import('@/api/reports')
    let result = null
    
    switch (reportType.value) {
      case 'daily':
        const startDate = dateRange.value[0].toISOString().split('T')[0]
        const endDate = dateRange.value[1].toISOString().split('T')[0]
        result = await api.getReportData('daily-summary', startDate, endDate)
        break
      case 'monthly':
        const year = monthValue.value.getFullYear()
        const month = monthValue.value.getMonth() + 1
        // 格式化月份为两位数
        const monthStr = month < 10 ? `0${month}` : `${month}`
        result = await api.getReportData('monthly-summary', `${year}-${monthStr}-01`, `${year}-${monthStr}-31`)
        break
      case 'yearly':
        const yearVal = yearValue.value.getFullYear()
        result = await api.getReportData('yearly-summary', `${yearVal}-01-01`, `${yearVal}-12-31`)
        break
      case 'channel':
        const chStartDate = dateRange.value[0].toISOString().split('T')[0]
        const chEndDate = dateRange.value[1].toISOString().split('T')[0]
        result = await api.getReportData('channel-analysis', chStartDate, chEndDate)
        break
      case 'product':
        const pdStartDate = dateRange.value[0].toISOString().split('T')[0]
        const pdEndDate = dateRange.value[1].toISOString().split('T')[0]
        result = await api.getReportData('product-analysis', pdStartDate, pdEndDate)
        break
    }
    
    if (result && result.data && result.data.status === 'success') {
      // 转换API返回的数据格式为前端需要的格式
      reportData.value = transformApiData(result.data.data)
      ElMessage.success('报表生成成功')
    } else {
      throw new Error('API返回数据格式不正确')
    }
  } catch (error) {
    console.error('生成报表失败:', error)
    ElMessage.error('生成报表失败: ' + error.message)
    reportData.value = null
  } finally {
    loading.value = false
  }
}

// 转换API返回的数据为前端需要的格式
const transformApiData = (apiData) => {
  // 这里需要根据实际API返回的数据结构进行转换
  // 以下是一个示例实现，实际情况需要根据API返回格式调整
  
  // 如果API返回的数据已经符合前端的格式，可以直接返回
  if (apiData.totalSales !== undefined) {
    return {
      ...apiData,
      // 确保数据格式正确
      salesGrowth: apiData.salesGrowth || 0,
      orderGrowth: apiData.orderGrowth || 0,
      averageGrowth: apiData.averageGrowth || 0,
      refundRate: apiData.refundRate || 0
    }
  }
  
  // 以下是兜底数据，理想情况下应该不会用到
  // 但保留此逻辑以防API不可用或数据格式不兼容
  return {
    totalSales: apiData.totalSales || 0,
    salesGrowth: apiData.salesGrowth || 0,
    orderCount: apiData.orderCount || 0,
    orderGrowth: apiData.orderGrowth || 0,
    averageOrder: apiData.averageOrder || 0,
    averageGrowth: apiData.averageGrowth || 0,
    refundAmount: apiData.refundAmount || 0,
    refundRate: apiData.refundRate || 0,
    salesTrend: apiData.salesTrend || [],
    paymentDistribution: apiData.paymentDistribution || {},
    channelDistribution: apiData.channelDistribution || [],
    topProducts: apiData.topProducts || []
  }
}

// 验证输入
const validateInput = () => {
  switch (reportType.value) {
    case 'daily':
      if (!dateRange.value || dateRange.value.length !== 2) {
        ElMessage.warning('请选择日期范围')
        return false
      }
      break
    case 'monthly':
      if (!monthValue.value) {
        ElMessage.warning('请选择月份')
        return false
      }
      break
    case 'yearly':
      if (!yearValue.value) {
        ElMessage.warning('请选择年份')
        return false
      }
      break
  }
  return true
}

// 导出报表
const exportReport = async () => {
  try {
    if (!reportData.value) {
      ElMessage.warning('请先生成报表')
      return
    }
    
    const api = await import('@/api/reports')
    let startDate, endDate, format = 'excel'
    
    switch (reportType.value) {
      case 'daily':
        startDate = dateRange.value[0].toISOString().split('T')[0]
        endDate = dateRange.value[1].toISOString().split('T')[0]
        await api.exportReport('daily-summary', startDate, endDate, format)
        break
      case 'monthly':
        const year = monthValue.value.getFullYear()
        const month = monthValue.value.getMonth() + 1
        const monthStr = month < 10 ? `0${month}` : `${month}`
        await api.exportReport('monthly-summary', `${year}-${monthStr}-01`, `${year}-${monthStr}-31`, format)
        break
      case 'yearly':
        const yearVal = yearValue.value.getFullYear()
        await api.exportReport('yearly-summary', `${yearVal}-01-01`, `${yearVal}-12-31`, format)
        break
      case 'channel':
        startDate = dateRange.value[0].toISOString().split('T')[0]
        endDate = dateRange.value[1].toISOString().split('T')[0]
        await api.exportReport('channel-analysis', startDate, endDate, format)
        break
      case 'product':
        startDate = dateRange.value[0].toISOString().split('T')[0]
        endDate = dateRange.value[1].toISOString().split('T')[0]
        await api.exportReport('product-analysis', startDate, endDate, format)
        break
    }
    
    ElMessage.success('报表导出成功')
  } catch (error) {
    console.error('导出报表失败:', error)
    ElMessage.error('导出报表失败: ' + error.message)
  }
}

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 获取支付方式名称
const getPaymentMethodName = (method) => {
  const methodMap = {
    'cash': '现金',
    'wechat': '微信支付',
    'alipay': '支付宝',
    'mixed': '混合支付'
  }
  return methodMap[method] || method
}

// 获取支付方式颜色
const getPaymentColor = (method) => {
  const colorMap = {
    'cash': '#409EFF',
    'wechat': '#67C23A',
    'alipay': '#E6A23C',
    'mixed': '#F56C6C'
  }
  return colorMap[method] || '#909399'
}

// 获取渠道颜色
const getChannelColor = (index) => {
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
  return colors[index % colors.length]
}
</script>

<style scoped>
.reports-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 15px;
}

.loading-container {
  margin-top: 30px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.overview-card {
  height: 120px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}

.card-compare {
  font-size: 14px;
  color: #909399;
}

.card-compare.up {
  color: #67C23A;
}

.card-compare.down {
  color: #F56C6C;
}

.chart-card {
  margin-bottom: 20px;
}

.two-column {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
  padding: 10px;
}

.mock-chart {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-placeholder {
  flex: 1;
  display: flex;
  align-items: flex-end;
  justify-content: space-around;
  padding-bottom: 10px;
}

.chart-bar {
  width: 40px;
  background-color: #409EFF;
  border-radius: 4px 4px 0 0;
  position: relative;
  transition: all 0.3s;
}

.chart-bar:hover {
  background-color: #66b1ff;
}

.bar-tooltip {
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  display: none;
}

.chart-bar:hover .bar-tooltip {
  display: block;
}

.chart-labels {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}

.chart-label {
  text-align: center;
  font-size: 12px;
  color: #909399;
}

.payment-distribution, .channel-distribution {
  padding: 10px;
}

.payment-item, .channel-item {
  margin-bottom: 15px;
}

.payment-name, .channel-name {
  margin-bottom: 5px;
  font-weight: bold;
}

.payment-bar-container, .channel-bar-container {
  height: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  position: relative;
  margin-bottom: 5px;
}

.payment-bar, .channel-bar {
  height: 100%;
  border-radius: 4px;
}

.payment-percentage, .channel-percentage {
  position: absolute;
  right: 10px;
  top: 0;
  line-height: 20px;
  color: white;
  font-size: 12px;
}

.payment-amount, .channel-amount {
  text-align: right;
  font-size: 14px;
}

.table-card {
  margin-bottom: 20px;
}
</style> 